#! /usr/bin/python
# -*- coding: utf-8 -*-
#######################################################################################
#                                                                                     #
#    File: main.py                                                                    #
#    Part of stage1st-cheater                                                         #
#    Home: http://stage1st-cheater.googlecode.com                                     #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
'''
Created on May 14, 2011

@author: flyxian
'''
import time
import random

import urllib2

import threading

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from ui.Core import *


import browser_bogus
import daily_job
import online_keeper
from user_agent_lib import get_random_user_agent

VERSION = "2.2.3"

daily_job_threads = []
online_keeper_threads = []

daily_job_accounts = [] 
online_keeper_accounts = []

app = QApplication(sys.argv)
window = MainWindow()   
online_keeper_update_timer = QTimer()
daily_job_update_timer = QTimer()

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s
    
class Daily_Job_Worker(threading.Thread):
    def __init__(self, username, passwd, itemdata):
        threading.Thread.__init__(self)
        self.browser = browser_bogus.Browser(username, passwd, get_random_user_agent())
        self.setDaemon(True)
        self.stopevent = threading.Event()
        self.itemdata = itemdata
        
    def run(self):
#        self.dataitem[2] = True
        submit_success = -1
        while not self.stopevent.isSet():
            try:
                self.itemdata[2] = _fromUtf8("正在登录")
                daily_job.login(self.browser)
                self.itemdata[2] = _fromUtf8("已登录")                while submit_success < 0:
                    try:
                        submit_success = daily_job.cheat(self.browser)
                        self.itemdata[2] = _fromUtf8("日常完成")
                        self.itemdata[3] = _fromUtf8(time.strftime("%y-%m-%d %H:%M:%S"))
                    except daily_job.ExamNotAvailable:
                        self.itemdata[2] = _fromUtf8("未到下一次任务时间")
                        break
            #print submit_success
                self.itemdata[2] = _fromUtf8("正在注销")
                daily_job.logout(self.browser)
                self.itemdata[2] = _fromUtf8("已注销")
            except urllib2.URLError:
                self.itemdata[2] = _fromUtf8("网络连接不正常")
            except urllib2.HTTPError, err:
                print err.code
            except daily_job.LoginFailed:
                self.itemdata[2] = _fromUtf8("登录失败")
            except:
                self.itemdata[2] = _fromUtf8("未知异常")
                pass
#            daily_job._perform_cheating(self.self.browser)
            time.sleep(daily_job.delay)
            
    def join(self, timeout=0):
#        self.dataitem[2] = False
        self.stopevent.set()
        threading.Thread.join(self, timeout)
        
class Online_Keeper_Worker(threading.Thread):
    def __init__(self, username, passwd, itemdata):
        threading.Thread.__init__(self)
        self.browser = browser_bogus.Browser(username, passwd, get_random_user_agent())
        self.setDaemon(True)
        self.stopevent = threading.Event()
        self.itemdata = itemdata
        
    def run(self):
#        self.dataitem[2] = True
        self.counter = 0
#        print "UA: ", self.browser.user_agent
        try:
            self.itemdata[2] = _fromUtf8("正在登录")
            online_keeper.login(self.browser)
            self.itemdata[2] = _fromUtf8("已登录")
            while not self.stopevent.isSet():
                try:
                    online_keeper.cheat(self.browser)
                    self.itemdata[2] = _fromUtf8("运行中")
                except urllib2.URLError:
                    self.itemdata[2] = _fromUtf8("网络连接不正常")
                except:
                    pass
                self.counter += 1
                if self.counter > 125:
                    points = online_keeper.time2point(self.browser)
                    self.itemdata[2] = _fromUtf8("兑换好人卡%d张" % points)
                    self.counter = 0
                #random behavior
                time.sleep(random.randint(0, 300) + 300)
                
            self.itemdata[2] = _fromUtf8("正在注销")
            online_keeper.logout(self.browser)
            self.itemdata[2] = _fromUtf8("已注销")
        except online_keeper.LoginFailed:
            self.itemdata[2] = _fromUtf8("登录失败")
        except urllib2.URLError:
            self.itemdata[2] = _fromUtf8("网络连接不正常")
        except urllib2.HTTPError, err:
            print err.code
        except:
            self.itemdata[2] = _fromUtf8("未知异常")
            pass
        
            
    def join(self, timeout=0):
#        self.dataitem[2] = False
        self.stopevent.set()
        threading.Thread.join(self, timeout)
        

def read_account(filename="accounts.conf"):
    file = open(filename, "r")
    lines = file.readlines()
    file.close()
    
    daily = 0
    online = 0
    
    for line in lines:
        if line[0] == "#":
            continue
        if line[0] == "o":
            account_data = line.strip().split(",")[1:]
            online_keeper_accounts.append([QString.fromUtf8(account_data[0]),
                                           QString.fromUtf8(account_data[1]),
                                           QString.fromUtf8('##')])
        if line[0] == "d":
            account_data = line.strip().split(",")[1:]
            daily_job_accounts.append([QString.fromUtf8(account_data[0]),
                                       QString.fromUtf8(account_data[1]),
                                       QString.fromUtf8('##'),
                                       QString.fromUtf8('##')])
        
def write_account(filename="accounts.conf"):
    file = open(filename, "w")
    for item in online_keeper_accounts:
        if QString.toUtf8(item[0]) == "##":
                continue
        file.write("o," + QString.toUtf8(item[0]) + "," + QString.toUtf8(item[1]) + "\n")
    for item in daily_job_accounts:
        if QString.toUtf8(item[0]) == "##":
                continue
        file.write("d," + QString.toUtf8(item[0]) + "," + QString.toUtf8(item[1]) + "\n")
        
    file.close()
        
        
#    print daily_job_threads
#    print online_keeper_threads
            
def start_online_keeper():
    window.online_keeper_start()
    print window.pushButton_online_keeper_start.state
    if window.pushButton_online_keeper_start.state:
        for item in online_keeper_accounts:
            if QString.toUtf8(item[0]) == "##":
                continue
            worker = Online_Keeper_Worker(QString.toUtf8(item[0]), 
                                          QString.toUtf8(item[1]), item) 
            online_keeper_threads.append(worker)
        for worker in online_keeper_threads:
            worker.start()
        print online_keeper_threads
        online_keeper_update_timer.start(2000)
    else:
        for worker in online_keeper_threads:
            worker.join()
            del worker
        online_keeper_update_timer.stop()
        
def start_daily_job():      
    window.daily_job_start()
    if window.pushButton_daily_job_start.state:
        for item in daily_job_accounts:
            if QString.toUtf8(item[0]) == "##":
                continue
            worker = Daily_Job_Worker(QString.toUtf8(item[0]), 
                                      QString.toUtf8(item[1]), item)
            daily_job_threads.append(worker)
        for worker in daily_job_threads:
            worker.start()
        daily_job_update_timer.start(2000)
    else:
        for worker in daily_job_threads:
            worker.join()
            del worker
            
        daily_job_update_timer.stop()
                
                


    


#if __name__ == "__main__":
#    signal.signal(signal.SIGINT, sigint_handler)
#    signal.signal(signal.SIGTERM, sigint_handler)
#    read_account()
#    start_all()
#    while True:
#        time.sleep(1000000)

if __name__ == "__main__":
    random.seed()
    try:
        read_account()
    except:
        QMessageBox.information(window, _fromUtf8("错误"),
                    _fromUtf8("无法打开账户文件accounts.conf"))
#    print daily_job_accounts
#    print online_keeper_accounts
#    app = QApplication(sys.argv)
#    window = MainWindow()
    window.update_online_keeper_account_list(online_keeper_accounts)
    window.update_daily_job_account_list(daily_job_accounts)
    window.init_display_properties()
    window.init_signals()
    QObject.connect(online_keeper_update_timer,
                    SIGNAL(_fromUtf8("timeout()")),
                    window.online_keeper_account_list.reset)
    QObject.connect(daily_job_update_timer,
                    SIGNAL(_fromUtf8("timeout()")),
                    window.daily_job_account_list.reset)
    QObject.connect(window.pushButton_online_keeper_start,
                    SIGNAL(QString.fromUtf8("clicked()")),
                    start_online_keeper)
    QObject.connect(window.pushButton_daily_job_start,
                    SIGNAL(QString.fromUtf8("clicked()")),
                    start_daily_job)
    QObject.connect(window.online_keeper_dataModel,
                    SIGNAL(QString.fromUtf8("dataChanged()")),
                    write_account)
    window.write_account_signal.connect(write_account)
    
    QApplication.setQuitOnLastWindowClosed(False)
    window.show()
    
    sys.exit(app.exec_())